package com.jrx.anytxn.transaction.job.verifyFile;

import com.jrx.anytxn.param.entity.PrProductTable;
import com.jrx.anytxn.param.service.product.IProductTableService;
import com.jrx.anytxn.transaction.config.VerifyFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.service.IVerifyFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;


/**
 * 合并对账文件
 */
@Configuration
@EnableConfigurationProperties(VerifyFileConfig.class)
public class MergeVerifyFileConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(MergeVerifyFileConfiguration.class);


    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private VerifyFileConfig verifyFileConfig;
    @Autowired
    private IProductTableService productTableService;
    @Autowired
    private IVerifyFileService verifyFileService;

    @Bean
    public Job mergeVerifyFileJob(){
        return jobBuilderFactory.get("mergeVerifyFileJob")
                .start(mergeVerifyFileStep())
                .build();
    }

    @Bean
    public Step mergeVerifyFileStep(){
        return stepBuilderFactory.get("mergeVerifyFileStep")
                .tasklet(mergeVerifyFileStepTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet mergeVerifyFileStepTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.debug("合并对账文件开始。。。。。。");
            List<PrProductTable> proList = productTableService.findAllVerifyForBatch(TransBizConstant.STATUS_1,TransBizConstant.STATUS_1);
            try {
                verifyFileService.mergeVerifyFile(proList,verifyFileConfig.getFilePath(),verifyFileConfig.getFileName());
            } catch (IOException e) {
                logger.error("合并文件异常：",e);
            }
            logger.debug("对账文件合并结束。。。。。。");
            return RepeatStatus.FINISHED;
        };
    }
}
